package com.ai.mall.service.impl;

import com.ai.mall.dao.CouponsDao;
import com.ai.mall.dao.OrdersDao;
import com.ai.mall.dao.ProductsDao;
import com.ai.mall.entity.*;
import com.ai.mall.enums.OrderStatus;
import com.ai.mall.service.OrderItemsService;
import com.ai.mall.service.OrdersService;
import com.ai.mall.utils.PageUtils;
import com.ai.mall.utils.Query;
import com.ai.mall.utils.R;
import com.ai.mall.vo.req.AddCartProductInfoRequest;
import com.ai.mall.vo.req.OrderSubmitRequest;
import com.ai.mall.vo.res.OrderVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


@Service("ordersService")
public class OrdersServiceImpl extends ServiceImpl<OrdersDao, OrdersEntity> implements OrdersService {

    @Autowired
    private ProductsDao productsDao;
    @Autowired
    private CouponsDao couponsDao;
    @Autowired
    private OrderItemsService orderItemsService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrdersEntity> page = this.page(
                new Query<OrdersEntity>().getPage(params),
                new QueryWrapper<OrdersEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public R submitOrder(OrderSubmitRequest orderSubmitRequest, UsersEntity userInfo) {
        // 计算订单总价
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (AddCartProductInfoRequest itemRequest : orderSubmitRequest.getCartItems()) {
            ProductsEntity product = productsDao.selectById(itemRequest.getProductId());
            if (product == null) {
                return R.error("商品不存在");
            }
            if (product.getStock() < itemRequest.getQuantity()) {
                return R.error("商品库存不足");
            }
            totalAmount = totalAmount.add(product.getPrice().multiply(BigDecimal.valueOf(itemRequest.getQuantity())));
        }

        // 计算应付金额（考虑优惠券）
        BigDecimal payableAmount = totalAmount;

        // 计算优惠券折扣
        BigDecimal couponDiscount = BigDecimal.ZERO;
        if (orderSubmitRequest.getCouponId() != null) {
            // 计算优惠券折扣
            CouponsEntity couponsEntity = couponsDao.selectById(orderSubmitRequest.getCouponId());
            if (couponsEntity == null) {
                return R.error("优惠券不存在");
            }
            if (couponsEntity.getStatus() != 0) {
                return R.error("优惠券已失效");
            }
            if (couponsEntity.getStartDate().after(new Date())) {
                return R.error("优惠券未生效");
            }
            if (couponsEntity.getEndDate().before(new Date())) {
                return R.error("优惠券已过期");
            }
            if (totalAmount.compareTo(couponsEntity.getMinPurchase()) < 0) {
                return R.error("订单金额不足");
            }

            payableAmount = totalAmount.subtract(couponsEntity.getDiscountAmount());
            // 更新优惠券状态
            couponsEntity.setStatus(1);
            couponsDao.updateById(couponsEntity);
        }
        // 计算运费
        BigDecimal shippingFee = orderSubmitRequest.getShippingFee();
        if (shippingFee != null) {
            payableAmount = payableAmount.add(shippingFee);
        }

        // 更新商品库存
        for (AddCartProductInfoRequest itemRequest : orderSubmitRequest.getCartItems()) {
            ProductsEntity product = productsDao.selectById(itemRequest.getProductId());
            product.setStock(product.getStock() - itemRequest.getQuantity());
            productsDao.updateById(product);
        }

        // 创建订单实体
        OrdersEntity order = new OrdersEntity();
        order.setUserId(userInfo.getUserId());
        order.setOrderNumber(System.currentTimeMillis() + "");
        order.setCouponId(orderSubmitRequest.getCouponId());
        order.setTotalAmount(totalAmount);
        order.setPayAmount(payableAmount);
        order.setOrderStatus(0); // 设置订单初始状态为“待付款”
        order.setCreatedAt(new Date());
        order.setShippingFee(shippingFee);
        order.setAddressesId(orderSubmitRequest.getAddressId());
        order.setDiscount(couponDiscount);
        this.save(order);

        // 创建订单详情实体列表
        Collection<OrderItemsEntity> orderItemsList = new ArrayList<>();
        for (AddCartProductInfoRequest itemRequest : orderSubmitRequest.getCartItems()) {
            OrderItemsEntity orderItem = new OrderItemsEntity();
            orderItem.setOrderId(order.getOrderId());
            orderItem.setProductId(itemRequest.getProductId());
            orderItem.setQuantity(itemRequest.getQuantity());
            orderItem.setProductPrice(itemRequest.getProductPrice());
            orderItemsList.add(orderItem);
        }
        orderItemsService.saveBatch(orderItemsList);
        return R.ok();
    }

    @Override
    public boolean cancelOrder(Integer id) {
        // 1. 检查订单是否存在
        OrdersEntity order = getById(id);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }

        // 2. 检查订单状态，只有待支付或待发货的订单可以取消
        if (!order.getOrderStatus().equals(0) && !order.getOrderStatus().equals(1)) {
            throw new RuntimeException("订单状态不允许取消");
        }

        // 3. 更新订单状态为已取消
        order.setOrderStatus(OrderStatus.CANCELLED.getStatus());
        save(order);

        // 4. 库存回滚（如果需要）
        List<OrderItemsEntity> orderItems = orderItemsService.getBaseMapper().selectList(new QueryWrapper<OrderItemsEntity>()
                .eq("order_id", id));
        for (OrderItemsEntity item : orderItems) {
            ProductsEntity product = productsDao.selectById(item.getProductId());
            if (product != null) {
                product.setStock(product.getStock() + item.getQuantity());
                productsDao.updateById(product);
            }
        }

        // 退回优惠券
        if (order.getCouponId() != null) {
            CouponsEntity couponsEntity = couponsDao.selectById(order.getCouponId());
            if (couponsEntity != null) {
                couponsEntity.setStatus(0);
                couponsDao.updateById(couponsEntity);
            }
        }
        return true;
    }

    @Override
    public List<OrderVO> getPendingPaymentOrders(UsersEntity userInfo) {
        // 1. 查询待支付订单
        return getOrdersByStatus(userInfo, OrderStatus.PENDING_PAYMENT);
    }

    @Override
    public List<OrderVO> getPendingReceiptOrders(UsersEntity userInfo) {
        return getOrdersByStatus(userInfo, OrderStatus.PENDING_RECEIPT);
    }

    @Override
    public List<OrderVO> getPendingReviewOrders(UsersEntity userInfo) {
        return getOrdersByStatus(userInfo, OrderStatus.PENDING_REVIEW);
    }

    @Override
    public List<OrderVO> getAllOrders(UsersEntity userInfo) {
        return getOrdersByStatus(userInfo, null);
    }

    @Override
    public void confirmReceipt(Integer orderId) {
        // 1. 查询订单
        OrdersEntity order = this.getById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }

        // 2. 更新订单状态为已完成
        order.setOrderStatus(OrderStatus.COMPLETED.getStatus());
        this.updateById(order);
    }

    @Override
    public void goPay(Integer orderId, UsersEntity userInfo) {
        // 1. 查询订单
        OrdersEntity order = this.getById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }

        // 2. 更新订单状态为待发货
        order.setOrderStatus(OrderStatus.PENDING_SHIPMENT.getStatus());
        this.updateById(order);
    }

    public List<OrderVO> getOrdersByStatus(UsersEntity userInfo, OrderStatus orderStatus) {
        // 1. 查询指定状态的订单
        List<OrdersEntity> orders = this.list(new QueryWrapper<OrdersEntity>()
                .eq("user_id", userInfo.getUserId())
                .eq(orderStatus != null,"order_status", orderStatus.getStatus()));

        // 2. 查询订单详情
        List<OrderItemsEntity> orderItemsList = orderItemsService.list(new QueryWrapper<OrderItemsEntity>()
                .in("order_id", orders.stream().map(OrdersEntity::getOrderId).collect(Collectors.toList())));

        // 3. 组装数据
        List<OrderVO> orderVOS = new ArrayList<>();
        for (OrdersEntity order : orders) {
            OrderVO orderVO = new OrderVO();
            orderVO.setOrderId(order.getOrderId());
            orderVO.setOrderNumber(order.getOrderNumber());
            orderVO.setPayAmount(order.getPayAmount());
            orderVO.setCreatedAt(order.getCreatedAt());
            orderVO.setOrderStatus(order.getOrderStatus());
            orderVO.setOrderStatusLabel(orderStatus.getStatusLabel());
            orderVO.setOrderItemList(orderItemsList.stream()
                    .filter(item -> item.getOrderId().equals(order.getOrderId()))
                    .collect(Collectors.toList()));
            orderVOS.add(orderVO);
        }
        return orderVOS;
    }


}